import React, { useEffect, useState } from 'react'
import { Table, message, Form, Space, Tag, Button, Modal, Drawer, Select, Input, Radio, Popconfirm, Pagination, Card } from "antd"
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, EditOutlined, CloseOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import api from '@/api'
import TextArea from 'antd/es/input/TextArea';



export default function Share() {
    const [query, setQuery] = useState({
        pageSize: 2,
        currentPage: 1
    })
    const [total, setTotal] = useState()
    let flag = true
    let flag2 = false

    const [singleshare, setSingleshare] = useState({
        detail: "",
        vedio: ""
    })
    const [form] = Form.useForm();
    const [form1] = Form.useForm();
    const [con, setCon] = useState(false)
    const [open, setOpen] = useState(false);
    const [closer, setCloser] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [sharelist, setSharelist] = useState([{
        id: "",
        vedio: "",
        class: "",
        createdAt: "",
        updatedAt: "",
        detail: "",
        serveid: "",
        title: "",
    }])
    const [list, setlist] = useState({
        vedio: "",
        class: "",
        createdAt: "",
        updatedAt: "",
        detail: "",
        serveid: "",
        title: "",
    })
    useEffect(() => {
        getSharelist(query)
    }, [])
    async function mohu(params: any, args: any) {
        console.log('awe', args);
        console.log('pramas', params);

        const res = await api.share.getShareByClassid({ ...params, classid: args })
        console.log('jj', res.data);
        setSharelist(res.data.data)
        setTotal(res.data.total)

    }
    const getSharelist = async (params: any) => {
        const res = await api.share.getAllShare(params)
        setTotal(res.data.total)
        console.log('ssss', res.data);
        setSharelist(res.data.data)
    }
    const onFinish = async (values: any) => {
        console.log('Success:', values);
        values.classid = Number(values.classid)
        console.log('Success:', values);
        const res = await api.share.updateShare(values)
        message.success(res.data.msg)
        setOpen(false);
        getSharelist(query)
    };
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    const onFinish1 = async (values: any) => {
        console.log('Success:', values);
        values.classid = Number(values.classid)
        const res = await api.share.addShare(values)
        message.success(res.data.msg)
        setCloser(false);
        getSharelist(query)
    };
    const onFinishFailed1 = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    const addShare = () => {
        console.log("新增帖子");
        setCloser(true);
    }
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const onClose = () => {
        form.resetFields()
        form1.resetFields()
        setOpen(false);
        setCloser(false);
    };
    const getDetail = async (arg: any, index: number) => {
        console.log("arg", arg, index);
        setSingleshare(sharelist[index])
        setIsModalOpen(true);
    }
    const deletethis = async (arg: any) => {
        console.log("arg", arg);
        setCon(arg.id)
        // const res = await api.share.deleteShare({ id: arg.id })
        // message.success(res.data.msg)
        // getSharelist()
    }
    const confirm = async () => {
        const res = await api.share.deleteShare({ id: con })
        message.success(res.data.msg)
        getSharelist(query)
    }
    const updateDetail = (arg: any, i: number) => {
        console.log("arg", arg);
        form.setFieldsValue({
            id: sharelist[i].id,
            vedio: sharelist[i].vedio,
            classid: Number(sharelist[i].class),
            detail: sharelist[i].detail,
            serveid: sharelist[i].serveid,
            title: sharelist[i].title,
        })
        setOpen(true);
    }
    let argss: any = ''
    const onChange = async (value: number | string) => {
        flag2 = false
        if (value == 4) {
            getSharelist({ ...query, currentPage: 1 })
            setQuery({ ...query, currentPage: 1 })
            flag = true
        } else {
            argss = value
            console.log(`selected ${value}`);
            console.log('sss', argss);
            setQuery({ ...query, currentPage: 1 })
            mohu({ ...query, currentPage: 1 }, argss)
            flag = false
        }

    };
    let val: any
    async function onFind(pramas: any) {

        const res = await api.share.SearchShare({ ...pramas, querystr: val })
        console.log('mohu', res.data.data);
        setSharelist(res.data.data)
        setTotal(res.data.total)



    }
    const onSearch = (value: number | string) => {
        console.log('search:', value);
        val = value
        onFind({ ...query, currentPage: 1 })

    };
    const columns: ColumnsType<any> = [
        {
            title: 'id',
            dataIndex: 'id',
        },
        {
            title: '员工',
            dataIndex: 'nickname',
        },
        {
            title: '标题',
            dataIndex: 'title',

        },
        {
            title: '热度',
            dataIndex: 'hot',

        },
        {
            title: '收藏量',
            dataIndex: 'fav',
        },
        {
            title: '类型',
            dataIndex: 'name',

        },
        {
            title: '发布日期',
            dataIndex: 'createdAt',
            render: (text, record) => (
                <>
                    {
                        text ? <>{text.slice(0, 16)}</> : <>{null}</>
                    }
                </>
            )
        },
        {
            title: '操作',
            dataIndex: 'id',
            render: (text, record, index) => (
                <Space size="middle">
                    <Button type="primary" shape="circle" icon={<SearchOutlined />} onClick={() => getDetail(record, index)} style={{ margin: '0 2px' }}></Button>

                    <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => updateDetail(record, index)} style={{ margin: '0 2px' }}></Button>
                    <Popconfirm
                        placement="top"
                        title={text}
                        description="确定删除吗"
                        onConfirm={confirm}
                        okText="Yes"
                        cancelText="No"
                    >
                        <Button type="primary" danger shape="circle" icon={<CloseOutlined />} onClick={() => deletethis(record)} style={{ margin: '0 2px' }}></Button>
                    </Popconfirm>

                </Space>
            ),
        },
    ];
    function pageChange(args: any) {
        if (!flag2) {
            if (flag) {
                getSharelist({ ...query, currentPage: args })
            } else {
                mohu({ ...query, currentPage: args }, argss)

            }
        } else {
            onFind({ ...query, currentPage: args })
        }


        setQuery({ ...query, currentPage: args })
    }
    return (
        <div>
            <Card>



                <div style={{ display: "flex", justifyContent: "space-between", margin: "10px" }}>
                    <div>
                        快捷搜索：
                        <Select
                            showSearch
                            placeholder="Select a person"
                            optionFilterProp="children"
                            onChange={onChange}
                            onSearch={onSearch}
                            filterOption={(input, option) =>
                                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                            }
                            options={[
                                {
                                    value: 1,
                                    label: '服务',
                                },
                                {
                                    value: 2,
                                    label: '维修',
                                },
                                {
                                    value: 3,
                                    label: '厨师',
                                },
                                {
                                    value: 4,
                                    label: '全部'
                                }
                            ]}
                        />
                    </div>
                    <Button onClick={addShare} type='primary' shape='round' >新增帖子</Button>
                </div>


                {
                    sharelist ? <>
                        <Table columns={columns} dataSource={sharelist} rowKey="id" pagination={false} />
                        <Modal title="Basic Modal" open={isModalOpen} onCancel={handleCancel} footer={null}>
                            <p>{singleshare.detail}</p>
                        </Modal>
                        <Drawer title="正在修改帖子" placement="right" onClose={onClose} open={open}>
                            <Form
                                name="basic"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }}
                                layout="vertical"
                                style={{ maxWidth: 600 }}
                                initialValues={{ remember: true }}
                                onFinish={onFinish}
                                onFinishFailed={onFinishFailed}
                                autoComplete="off"
                                form={form}
                            >
                                <Form.Item label="帖子id" name="id" >
                                    <Input disabled></Input>
                                </Form.Item>
                                <Form.Item label="标题" name="title" rules={[{ required: true, message: "请填写" }]}>
                                    <Input ></Input>
                                </Form.Item>
                                <Form.Item label="员工id" name="serveid" rules={[{ required: true, message: "请填写" }]}>
                                    <Input ></Input>
                                </Form.Item>
                                <Form.Item label="详情" name="detail" rules={[{ required: true, message: "请填写" }]}>
                                    <TextArea ></TextArea>
                                </Form.Item>
                                <Form.Item label="上传视频" name="vedio" rules={[{ required: true, message: "请填写" }]}>
                                    <Input ></Input>
                                </Form.Item>
                                <Form.Item label="帖子类型" name="classid" rules={[{ required: true, message: "请填写" }]}>
                                    <Radio.Group >
                                        <Radio value="1"> 服务 </Radio>
                                        <Radio value="2"> 维修 </Radio>
                                        <Radio value="3"> 厨师 </Radio>
                                    </Radio.Group>
                                </Form.Item>
                                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                    <Button type="primary" htmlType="submit">
                                        Submit
                                    </Button>
                                </Form.Item>
                            </Form>
                        </Drawer>
                        <Drawer title="正在新增帖子" placement="right" onClose={onClose} open={closer}>
                            <Form
                                name="basic"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }}
                                layout="vertical"
                                style={{ maxWidth: 600 }}
                                initialValues={{ remember: true }}
                                onFinish={onFinish1}
                                onFinishFailed={onFinishFailed1}
                                autoComplete="off"
                                form={form1}
                            >
                                <Form.Item label="标题" name="title" rules={[{ required: true, message: "请填写" }]}>
                                    <Input ></Input>
                                </Form.Item>
                                <Form.Item label="员工id" name="serveid" rules={[{ required: true, message: "请填写" }]}>
                                    <Input ></Input>
                                </Form.Item>
                                <Form.Item label="详情" name="detail" rules={[{ required: true, message: "请填写" }]}>
                                    <TextArea ></TextArea>
                                </Form.Item>
                                <Form.Item label="上传视频" name="vedio" rules={[{ required: true, message: "请填写" }]}>
                                    <Input ></Input>
                                </Form.Item>
                                <Form.Item label="帖子类型" name="classid" rules={[{ required: true, message: "请填写" }]}>
                                    <Radio.Group >
                                        <Radio value="1"> 服务 </Radio>
                                        <Radio value="2"> 维修 </Radio>
                                        <Radio value="3"> 厨师 </Radio>
                                    </Radio.Group>
                                </Form.Item>
                                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                    <Button type="primary" htmlType="submit">
                                        Submit
                                    </Button>
                                </Form.Item>
                            </Form>
                        </Drawer>
                        <Pagination total={total} pageSize={query.pageSize} current={query.currentPage} onChange={pageChange}></Pagination>
                    </> : <></>
                }
            </Card>
        </div >
    )
}
